import axios from 'axios';

// 创建axios实例
const api = axios.create({
    baseURL: '/api', // 与Vite代理匹配
    headers: {
        'Content-Type': 'application/json;charset=utf-8'
    }
});

// 请求拦截器 - 添加Authorization头
api.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('Authorization')?.trim(); // 清除首尾空格
        if (token) {
            config.headers.Authorization = `Bearer ${token.trim()}`;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);


// 定义不需要拦截的API路径白名单
const whiteList = [
    '/',
    '/User/PasswordLogin',
    '/User/SmsLogin',
    '/User/Register',
    '/Public/GetInfo',
    '/SmsSend',
    '/SmsVerify',
    "/SlideCaptchaVerify",
    '/public/actor/actorquery',
    '/public/marksheet/query',
    '/public/slideshow/query',
    '/public/cinema/query',
    '/public/film/query',
    '/public/film/queryall',
    '/CinemaView',
    '/FilmView',
    "/public/homepage/query/{id}",
    "/public/homepage/queryall",
    "/public/comment/query/{id}",
    '/public/maoyanmovieproject/getAllPerformanceOrder',
    '/public/maoyanmovieproject/addPerformanceOrder',
    '/public/maoyanmovieproject/deletePerformanceOrderById/{id}',
    '/public/maoyanmovieproject/selectAllPerformanceOrderByUserId/{id}',
    '/public/maoyanmovieproject/queryPerformanceById/{id}',
    '/public/maoyanmovieproject/queryAllPerformance',
    '/public/maoyanmovieproject/queryPerformanceByType/{type}',
    '/public/maoyanmovieproject/queryRecommendByType/{type}',
    '/public/maoyanmovieproject/queryFunctionBarById/{id}',
    '/public/maoyanmovieproject/queryAllFunctionBar'
];

// 响应拦截器 - 处理token过期等
api.interceptors.response.use(
    (response) => {
        return response;
    },
    (error) => {
        // 检查请求是否在白名单中
        const isWhiteListed = whiteList.some(path =>
            error.config.url.includes(path)
        );

        // 白名单接口或非401错误直接放行
        if (isWhiteListed || error.response.status !== 401) {
            return Promise.reject(error);
        }

        // 仅处理需要登录的401错误
        localStorage.removeItem('Authorization');
        localStorage.removeItem('userId');
        window.location.href = '/LoginView';
        return Promise.reject(error);
    }
);

export default api;